<template>
  <div class="tab-menu">
    <a-tabs
      :hideAdd="true"
      v-model="activeKey"
      type="editable-card"
      @edit="onEdit"
      @tabClick="onTabClick"
    >
      <a-tab-pane
        v-for="(pane, index) in this.tabs"
        :key="pane.id"
        :tab="pane.title"
        :closable="index !== 0"
      />
    </a-tabs>
  </div>
</template>

<script>
import emitter from '@/utils/emitter';
import Events from '@/utils/event';
import { some } from 'lodash-es';

export default {
  name: 'TabMenu',
  data () {
    return {
      tabs: [{ id: 0, path: 'dashboard', title: 'Dashboard' }],
      activeKey: 0
    };
  },
  methods: {
    getPathById (targetKey) {
      let path;
      some(this.tabs, item => {
        if (targetKey === item.id) {
          path = '/' + item.path;
        }
      });
      return path;
    },
    onTabClick (targetKey) {
      const path = this.getPathById(targetKey);
      this.$router.push(path);
    },
    onEdit (targetKey, action) {
      this[action](targetKey);
    },
    remove (targetKey) {
      let deleteIndex;
      // 获取要删除的索引
      this.tabs.some((item, index) => {
        if (item.id === targetKey) {
          deleteIndex = index;
          return true;
        }
      });
      // 删除当前项
      this.tabs.splice(deleteIndex, 1);

      // 删除项不是高亮状态
      if (targetKey === this.activeKey) {
        // 索引-1，设置activeKey
        this.activeKey = this.tabs[deleteIndex - 1].id;
        // 路由跳转
        const path = this.getPathById(this.activeKey);
        this.$router.replace({ path });
      }
    },
    addTab (data) {
      const flag = some(this.tabs, item => {
        if (data.id === item.id) {
          return true;
        }
      });
      if (!flag) {
        this.tabs.push(data);
      }
      this.activeKey = data.id;
    }
  },
  created () {
    emitter.on(Events.ADD_TAB, this.addTab);
  },
  beforeDestroy () {
    emitter.off(Events.ADD_TAB, this.addTab);
  }
};
</script>

<style scoped lang="less">
.tab-menu {
  //background: #e7e6ea !important;

  /deep/ .ant-tabs {
    height: 30px;
  }

  /deep/ .ant-tabs-bar {
    margin-bottom: 0;
    border-bottom: none;
  }

  /deep/ .ant-tabs.ant-tabs-card .ant-tabs-card-bar .ant-tabs-nav-container {
    height: auto;
  }

  /deep/ .ant-tabs-nav-container {
    height: 30px;
  }

  /deep/ .ant-tabs.ant-tabs-card .ant-tabs-card-bar .ant-tabs-tab {
    height: 30px;
    line-height: 30px;
    margin-right: 10px;
    font-size: 12px;

    &:hover {
      color: #1890ff;
    }
  }

  /deep/ .ant-tabs-tab {
    color: #7B6F86;
    background: #e7e6ea !important;
  }

  /deep/ .ant-tabs-card-content {
    display: none;
  }

  /deep/ .ant-tabs-nav .ant-tabs-tab-active {
    font-weight: normal;
  }
}
</style>
